<template>
  <div>
    <!-- 遮罩层 -->
    <div
      class="modal-overlay"
      :style="{ display: visible ? 'flex' : 'none' }"
      @click="onOverlayClick"
    >
      <div class="modal-container" @click.stop>
        <button class="close-btn" @click="close">
          <i class="fas fa-times"></i>
        </button>
        <iframe
          id="previewIframe"
          ref="iframeRef"
          :src="computedSrc"
          frameborder="0"
          scrolling="auto"
          style="width: 100%; height: 100%"
        ></iframe>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, defineExpose, ref, watch } from 'vue'
import type { DocumentPreviewProps, PreviewOptions } from './types'
import { defaultPreviewOptions } from './types'

const props = defineProps<DocumentPreviewProps>()

const visible = ref(false)
const iframeRef = ref<HTMLIFrameElement | null>(null)

// 运行时的状态：当前使用的file与ops（用于open的覆盖）
const runtimeFile = ref<string | undefined>(undefined)
const runtimeOps = ref<PreviewOptions | undefined>(undefined)

// 合并默认ops、props.ops与runtimeOps（优先级：default < props.ops < runtimeOps）
const mergedOps = computed<PreviewOptions>(() => ({
  ...defaultPreviewOptions,
  ...(props.ops || {}),
  ...(runtimeOps.value || {}),
}))

// 基础预览服务地址（内部根据file自动构造xurl）
const VIEW_BASE = 'https://view.xdocin.com/view?src='

// 计算iframe的src，file优先级：runtimeFile > props.file
const computedSrc = computed(() => {
  const fileUrl = runtimeFile.value ?? props.file
  if (!fileUrl) return ''

  let url = VIEW_BASE + encodeURIComponent(fileUrl)
  const sep = url.includes('?') ? '&' : '?'
  const queries: string[] = []
  Object.entries(mergedOps.value).forEach(([k, v]) => {
    if (v === undefined || v === null || v === '') return
    queries.push(`${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
  })
  if (queries.length > 0) {
    if (url.endsWith('?') || url.endsWith('&')) {
      url += queries.join('&')
    } else {
      url += sep + queries.join('&')
    }
  }
  return url
})

function open(file?: string, opsOverride?: PreviewOptions) {
  // 记录本次调用传入的覆盖参数
  runtimeFile.value = file ?? runtimeFile.value ?? props.file
  runtimeOps.value = opsOverride ?? runtimeOps.value
  visible.value = true
}

function close() {
  visible.value = false
  // 清空src以释放资源，并清理一次性覆盖参数
  if (iframeRef.value) {
    iframeRef.value.src = ''
  }
  // 仅关闭时清除本次运行态参数，保留组件级默认props
  runtimeFile.value = undefined
  runtimeOps.value = undefined
}

function onOverlayClick(e: MouseEvent) {
  if (e.target && (e.target as HTMLElement).classList.contains('modal-overlay')) {
    close()
  }
}

// 对外暴露方法
defineExpose({ open, close })

// 当visible变化时，进入时设置src，关闭时清空
watch(visible, (val) => {
  if (val) {
    if (iframeRef.value) {
      iframeRef.value.src = computedSrc.value
    }
  } else {
    if (iframeRef.value) iframeRef.value.src = ''
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.55);
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  /* 背景毛玻璃效果，提升对比度 */
  backdrop-filter: blur(2px);
  -webkit-backdrop-filter: blur(2px);
}
.modal-container {
  width: 80%;
  max-width: 1000px;
  height: 80vh;
  background: #ffffff;
  border-radius: 12px;
  position: relative;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.25);
  overflow: hidden;
  animation: modalIn .18s ease-out;
}
@keyframes modalIn {
  from { transform: translateY(8px) scale(0.985); opacity: 0; }
  to   { transform: translateY(0)    scale(1);     opacity: 1; }
}
.close-btn {
  position: absolute;
  top: 25px;
  right: 15px;
  background: #bbb6b6;
  color: white;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  cursor: pointer;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color .15s ease, transform .1s ease;
}
.close-btn:hover { background: #398DFF; }
.close-btn:active { transform: scale(0.96); }

#previewIframe {
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 12px;
}

/* 移动端适配 */
@media (max-width: 640px) {
  .modal-container {
    width: 96%;
    height: 88vh;
    max-width: none;
    border-radius: 10px;
  }
}
</style>
